package com.daJiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daJiao.domain.SecurityUserDetails;
import com.daJiao.entity.SysMenu;
import com.daJiao.entity.SysRoleMenu;
import com.daJiao.entity.SysUser;
import com.daJiao.entity.SysUserRole;
import com.daJiao.enums.UserStatusEnum;
import com.daJiao.exception.BusinessException;
import com.daJiao.service.SysMenuService;
import com.daJiao.service.SysRoleMenuService;
import com.daJiao.service.SysUserRoleService;
import com.daJiao.service.SysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>Title:	  SecurityUserDetailsService <br/> </p>
 * <p>Description 用户信息Service <br/> </p>
 * <p>Company:    医百科技有限公司  <br/> </p>
 *
 * @Author <a href="yangwensheng@100doc.com.cn"/>杨文生</a>  <br/>
 * @Date 2021/12/07 14:45
 */
@Service
public class SecurityUserDetailsService implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public SecurityUserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.loadUserByUsername(userName);
        if(Objects.isNull(sysUser)){
            throw new BadCredentialsException("用户名或密码错误");
        }

        if(UserStatusEnum.DISABLE.getKey() == sysUser.getStatus()){
            throw new DisabledException("账号被禁用");
        }

        // 查询这个用户又哪儿些角色
        List<SysUserRole> sysUserRoles = sysUserRoleService.list(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, sysUser.getId()));
        if(CollectionUtils.isEmpty(sysUserRoles)){
            throw new BusinessException("请联系管理员绑定角色");
        }

        List<String> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());

        // 查询角色所绑定的权限信息
        List<SysRoleMenu> roleMenus = sysRoleMenuService.getMenuByRoleIds(roleIds);
        if(CollectionUtils.isEmpty(roleMenus)){
            throw new BusinessException("请联系管理员给角色绑定对应菜单信息");
        }

        List<SysMenu> menus = sysMenuService.listByIds(roleMenus.stream().map(SysRoleMenu::getMenuId).distinct().collect(Collectors.toList()));

        return new SecurityUserDetails(sysUser, menus.stream().map(SysMenu::getUrl).collect(Collectors.toList()));
    }
}
